'use server';

import API_ENDPOINTS from '@/lib/apiEndpoints';
import type { CaptchaResults } from '@/types/captcha';
import { actionClient } from '@gm/auth/server';
import { apiRequest, type ApiResponse } from '@gm/base/server';
import z from 'zod';

const CaptchaType = ['blockPuzzle', 'clickWord'] as const;

export const getCaptcha = actionClient
  .inputSchema(
    z.object({
      captchaType: z.enum(CaptchaType),
    }),
  )
  .action(async ({ parsedInput }) => {
    const { result } = await apiRequest<ApiResponse<CaptchaResults>>(
      API_ENDPOINTS.CAPTCHA.GET,
      {
        method: 'POST',
        body: parsedInput,
      },
    );
    return result;
  });

const verifyCaptchaSchema = z.object({
  captchaType: z.enum(CaptchaType),
  pointJson: z.string(),
  token: z.string(),
});

// 从 zod 模式推导 TypeScript 类型
export type VerifyCaptchaInput = z.infer<typeof verifyCaptchaSchema>;

export const verifyCaptcha = actionClient
  .inputSchema(verifyCaptchaSchema)
  .action(async ({ parsedInput, ctx: {} }) => {
    const { result } = await apiRequest<ApiResponse<CaptchaResults>>(
      API_ENDPOINTS.CAPTCHA.VERIFY,
      {
        method: 'POST',
        body: parsedInput,
      },
    );
    return result;
  });
